import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Yinzi Chen
 * @date Nov 13, 2013
 */
public class MySemaphore {
    private Lock mutex;
    private Condition cond;
    private int resource;

    public MySemaphore(int permits) {
        mutex = new ReentrantLock();
        cond = mutex.newCondition();
        resource = permits;
    }

    public void acquire(int permits) throws InterruptedException {
        mutex.lock();
        try {
            while (resource < permits) {
                cond.await();
            }
            resource -= permits;
        } catch (InterruptedException e) {
            throw e;
        } finally {
            mutex.unlock();
        }
    }

    public void release(int permits) {
        mutex.lock();
        resource += permits;
        mutex.unlock();
    }
}
